<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\FollowsRequest;
use App\Http\Resources\BookResource;
use App\Http\Resources\WordResource;
use App\Models\Book;
use App\Models\Followable;
use App\Models\Word;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Jiannei\Response\Laravel\Support\Facades\Response;

class FollowController extends Controller
{
    // 收藏
    public function follow($type, $id)
    {
        if (in_array($type, Followable::TYPE_MAP)) {
            Response::errorBadRequest('收藏类型有误');
        }

        $model = Followable::TYPE_MAP[$type];
        $model::query()->findOrFail($id);

        $relation = Str::plural($type);
        $query = auth()->user()->{$relation}();
        $follows = $query->pluck('followable_id')->unique();
        if (!$follows->contains($id)) {
            $query->attach($id);
        }

        return Response::ok();
    }

    // 取消收藏
    public function unFollow($type, $id)
    {
        if (in_array($type, Followable::TYPE_MAP)) {
            Response::errorBadRequest('收藏类型有误');
        }

        $model = Followable::TYPE_MAP[$type];
        $model::query()->findOrFail($id);

        $relation = Str::plural($type);
        auth()->user()->{$relation}()->detach($id);

        return Response::ok();
    }

    // 收藏列表
    public function follows($type)
    {
        $user = auth()->user();
        if ($type == 'book') {
            $data = $user->books()->get();
            $resource = BookResource::class;
        } elseif ($type == 'word') {
            $data = $user->words()->get();
            $resource = WordResource::class;
        } else {
            Response::errorBadRequest('收藏类型有误');
        }

        return Response::success($resource::collection($data));
    }
}
